package com.hbnu.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author kittychen
 * @since 2025-10-30 20:10
 */
public class TcpServerDemo02 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(8888);  // 1、创建ServerSocket对象，指定端口号

            Socket socket = serverSocket.accept();

            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            byte[] buffer = new byte[1024];
            int len = inputStream.read(buffer);
            System.out.println("客户端发送的数据：" + new String(buffer, 0, len));

            outputStream.write("地瓜地瓜，我是土豆，收到，over".getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
